package cdkey

import (
	"context"
	"encoding/json"
	v1 "goGameWebServer/api/cdkey/v1"
	"goGameWebServer/internal/common/utils"
	"goGameWebServer/internal/controller"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/entityName"
	"goGameWebServer/internal/model/entity"
	"goGameWebServer/internal/register"

	"github.com/gogf/gf/v2/frame/g"
)

func (c *CdKeyControllerV1Private) Use(ctx context.Context, req *v1.CdKeyUseReq) (res *v1.CdKeyUseRes, err error) {
	isExist := entity.CodeIsExist(req.Code)
	if !isExist {
		controller.BackResponseError(g.RequestFromCtx(ctx), cerror.CDKEY_NOT_EXIST_ERROR,
			cerror.GetErrMsg(cerror.CDKEY_NOT_EXIST_ERROR))
		return
	}
	codeModel := register.GetModel(entityName.EntityName_CdKey)
	codeData := codeModel.GetEntityData().(*entity.CdKeyModelData)
	codeData.Code = req.Code
	codeModel.LoadEntityDataFromDB(nil)
	isExist = entity.CdKeyGroupIdIsExist(codeData.GroupId)
	if !isExist {
		controller.BackResponseError(g.RequestFromCtx(ctx), cerror.CDKEY_GROUP_NOT_EXIST_ERROR,
			cerror.GetErrMsg(cerror.CDKEY_GROUP_NOT_EXIST_ERROR))
		return
	}
	if codeData.UsedCount >= codeData.CanUseCount {
		controller.BackResponseError(g.RequestFromCtx(ctx), cerror.CDKEY_USED_OVER_ERROR,
			cerror.GetErrMsg(cerror.CDKEY_USED_OVER_ERROR))
		return
	}

	if codeData.LimitTime != "" {
		// 解析跟当前时间对比,看是否已经过了使用时间
		limitTimeStmp := utils.GetTimestampSecond(codeData.LimitTime)
		nowStmp := utils.GetNowTimestampSecond()
		if nowStmp > limitTimeStmp {
			controller.BackResponseError(g.RequestFromCtx(ctx), cerror.CDKEY_LIMIT_OVER_ERROR,
				cerror.GetErrMsg(cerror.CDKEY_LIMIT_OVER_ERROR))
			return
		}
	}
	// 看看这个角色是不是已经使用过这个cdkey了
	cdkeyUseModel := register.GetModel(entityName.EntityName_CdKeyUse)
	cdkeyUseData := cdkeyUseModel.GetEntityData().(*entity.CdKeyUseModelData)
	cdkeyUseData.UserId = req.AvatarId
	cdkeyUseModel.LoadEntityDataFromDB(nil)
	useCodes := []string{}
	if cdkeyUseData.Codes != "" {
		json.Unmarshal([]byte(cdkeyUseData.Codes), &useCodes)
	}
	// 判断这个角色是否已经使用过这个cdkey了
	for _, v := range useCodes {
		if v == req.Code {
			controller.BackResponseError(g.RequestFromCtx(ctx), cerror.CDKEY_HAS_USED_ERROR,
				cerror.GetErrMsg(cerror.CDKEY_HAS_USED_ERROR))
			return
		}
	}
	// 增加到useCodes
	useCodes = append(useCodes, req.Code)
	useDatas, _ := json.Marshal(useCodes)
	cdkeyUseData.Codes = string(useDatas)
	cdkeyUseModel.SaveEntityDataToDB()
	// 修改code的已使用次数
	codeData.UsedCount++
	codeModel.SaveEntityDataToDB()
	// 查询CDKEY Group信息
	groupModel := register.GetModel(entityName.EntityName_CdKeyGroup)
	groupData := groupModel.GetEntityData().(*entity.CdKeyGroupModelData)
	groupData.Id = codeData.GroupId
	groupModel.LoadEntityDataFromDB(nil)

	controller.BackResponseOK(g.RequestFromCtx(ctx), groupData.Extra)
	return
}
